package cn.xin.org.service.impl;

import cn.xin.base.query.BaseQuery;
import cn.xin.base.service.impl.BaseServiceImpl;
import cn.xin.base.util.PageList;
import cn.xin.org.domain.Employee;
import cn.xin.org.mapper.EmployeeMapper;
import cn.xin.org.service.IEmployeeService;
import cn.xin.org.vo.EmpAndRoleVo;
import cn.xin.system.mapper.RoleMapper;
import cn.xin.user.domain.Logininfo;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public List<Employee> findByDeptId(Long deptId) {
        return employeeMapper.findByDeptId(deptId);
    }


    @Override
    public void add(Employee employee) {
        //员工
        super.add(employee);
        //角色
        roleMapper.addEmpRole(employee.getId(),employee.getRoles());
    }

    @Override
    public void update(Employee emp) {
        super.update(emp);
        // 删除
        roleMapper.deleteByEmpId(emp.getId());
        // 角色
        roleMapper.addEmpRole(emp.getId(),emp.getRoles());
    }

    @Override
    public void delete(Long id) {
        super.delete(id);
        roleMapper.deleteByEmpId(id);
    }


    @Override
    public PageList<Employee> queryByPage(BaseQuery query) {
        //获取emp集合
        PageList<Employee> empPageList = super.queryByPage(query);

        if(empPageList == null || CollectionUtils.isEmpty(empPageList.getRows())){
            return empPageList;
        }
        //获取当前页的数据
        List<Employee> empList = empPageList.getRows();
        //获取当前页的id集合
        List<Long> empIdList = empList.stream().map(Employee::getId).collect(Collectors.toList());

        //
        List<EmpAndRoleVo> vos = roleMapper.findByEmpIds(empIdList);
        // 分组，key为Employee的Id，value为RoleId的集合
        Map<Long, List<Long>> voMap = vos.stream().collect(Collectors.groupingBy(EmpAndRoleVo::getEmployeeId
                , Collectors.mapping(EmpAndRoleVo::getRoleId, Collectors.toList())));

        empList.forEach(emp -> {
            List<Long> roleIds = voMap.get(emp.getId());
            emp.setRoles(roleIds);
        });
        return empPageList;
    }
}
